<template>
  <div class="message-container" ref="container" @scroll="debounceHandleScroll">
    <MessageArea
      @submit="handleSubmit"
      :isListLoading="isListLoading"
      title="留言板"
      :subTitle="data.total"
      :commentList="data.rows"
    />
  </div>
</template>

<script>
import MessageArea from "../components/MessageArea.vue";
import { getMessages, postMessage } from "../api/message.js";
import debounce from "../utils/debounce.js";

export default {
  components: {
    MessageArea,
  },
  data() {
    return {
      data: {},
      page: 1,
      limit: 10,
      isListLoading: false,
    };
  },
  async created() {
    this.$bus.$on("setMainScroll", this.handleSetMainScroll);
    this.isListLoading = true;
    this.data = await getMessages(this.page, this.limit);
    this.isListLoading = false;
  },
  destroyed() {
    this.$bus.$emit("mainScroll", null);
    this.$bus.$off("setMainScroll", this.handleSetMainScroll);
  },
  methods: {
    async handleSubmit(messageInfo, callback) {
      const resp = await postMessage(messageInfo);
      this.data.rows.unshift(resp);
      this.data.total++;
      callback("评论成功");
    },
    debounceHandleScroll(e) {
      if (!this.handleScrollDebounce) {
        this.handleScrollDebounce = debounce(this.handleScroll);
      }
      this.handleScrollDebounce(e);
    },
    async handleScroll(e) {
      this.$bus.$emit("mainScroll", e.target);
      const container = e.target;
      if (
        !this.data.rows ||
        this.isListLoading ||
        this.data.rows.length >= this.data.total
      ) {
        return;
      }
      if (
        container.scrollTop + container.clientHeight >=
        container.scrollHeight - 10
      ) {
        this.page++;
        this.isListLoading = true;
        const resp = await getMessages(this.page, this.limit);
        this.isListLoading = false;
        this.data.total = resp.total;
        this.data.rows = this.data.rows.concat(resp.rows);
      }
    },
    handleSetMainScroll(scrollTop) {
      this.$refs.container.scrollTop = scrollTop;
    },
  },
};
</script>

<style scoped lang="less">
.message-container {
  width: 100%;
  height: 100%;
  padding: 25px 200px;
  overflow-y: auto;
  scroll-behavior: smooth;
}
</style>